import { toJS } from "mobx";
import * as React from 'react';
import { Input, Tooltip, message, Dropdown, Menu, Row, Col } from 'antd';
import { WeaInput, WeaBrowser, WeaDatePicker, WeaLocaleProvider, WeaError } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
export default class KanbanGroup extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            taskInfo: {
                taskName: "",
                hrmid: "",
                startDate: this.getNowFormatDate(),
                endDate: this.getNowFormatDate(),
                hrmname: ""
            },
            userInfo: {
                userid: "",
                username: "",
                usericons: ""
            },
            groupName: "",
            baseGroupName:"",
            editGroupNameVisible: false,
        }
    }
    componentDidMount() {
        if (this.head && this.body && this.footer) {
            this.body.style.height = `${this.container.clientHeight - 20 - this.head.clientHeight - this.footer.clientHeight}px`
        }
        const { userInfo, title } = this.props;
        this.setState({
            taskInfo: {
                taskName: "",
                hrmid: userInfo.userid,
                hrmname: userInfo.username,
                startDate: this.getNowFormatDate(),
                endDate: this.getNowFormatDate(),
            },
            userInfo: {
                userid: userInfo.userid,
                username: userInfo.username,
                usericons: userInfo.usericons
            },
            groupName: title,
            editGroupNameVisible: false,
        });

    }

    componentWillMount() {
        const { title } = this.props;
        this.setState({
            groupName: title,
            baseGroupName : title,
            editGroupNameVisible: false,
        });
    }
    componentDidUpdate(prevProps, prevState) {
        // if (this.head && this.body && this.footer) {
        //     debugger;
        //     this.body.style.height = `${this.container.clientHeight - 20 - this.head.clientHeight }px`
        // }
    }
    componentWillUpdate(nextProps, nextState) {

    }
    componentWillReceiveProps(nextProps, nextState) {

        if (this.props.groupid !== nextProps.groupid || this.props.userInfo !== nextProps.userInfo) {
            const { userInfo, title } = nextProps;
            this.setState({
                taskInfo: {
                    taskName: "",
                    hrmid: userInfo.userid,
                    hrmname: userInfo.username,
                    startDate: this.getNowFormatDate(),
                    endDate: this.getNowFormatDate(),
                },
                userInfo: {
                    userid: userInfo.userid,
                    username: userInfo.username,
                    usericons: userInfo.usericons
                },
                groupName: title,
                editGroupNameVisible: false,
            });
        }
    }


    checkGroupRepeat = (name, id) => {
        let checked = true;
        const stages = toJS(this.props.columns);
        stages.map(item => {
            if (item.id !== id && item.title == name) {
                checked = false;
            }
        });
        return checked;
    }

    editGropName = (visible) => {
        if (!visible) {
            if (!this.state.groupName) {
                message.error("阶段名称必填！");
            } else {
                if(this.state.groupName !== this.state.baseGroupName){
                    const repeat = this.checkGroupRepeat(this.state.groupName, this.props.groupid);
                    if (repeat) {
                        this.props.saveGroupName(this.state.groupName, this.props.groupid);
                        this.setState({ editGroupNameVisible: visible });
                    } else {
                        message.error(getLabel('387703',"阶段名称重复！"));
                    }
                }else{
                    this.setState({ editGroupNameVisible: visible });
                }
            }
        } else {
            this.setState({ editGroupNameVisible: visible });
        }

    }
    render() {
        const { title, extra, value, canEditBoard, canAddTask } = this.props;
        let taskName = "";
        const menu = (
            <Menu ecId={`${this && this.props && this.props.ecId || ''}_Menu@fct2wf`}>
                <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_MenuItem@00fd8z`} key="0">
                    <span onClick={() => this.editGropName(true)}>{getLabel('387705', "修改阶段名称")}</span>
                </Menu.Item>
                <Menu.Divider ecId={`${this && this.props && this.props.ecId || ''}_MenuDivider@s8js2p`} />
                <Menu.Item ecId={`${this && this.props && this.props.ecId || ''}_MenuItem@9ddzgn`} key="1">
                    <span onClick={() => this.props.delGrop(this.props.groupid)}>{getLabel('387706', "删除阶段")}</span>
                </Menu.Item>
            </Menu>
        );
        return (
            <div data-value={value} className="kanban-group" ref={ref => this.container = ref} onClick={()=>{this.editGropName(false)}}>
                <div ref={ref => this.head = ref} className="kanban-group-head" onMouseDown={this.handleHeadMouseDown}>
                    <div className="kanban-group-head-wrapper">
                        <div className="kanban-group-head-title"  onClick={(e)=>{e.stopPropagation();this.editGropName(true)}}>
                            {!this.state.editGroupNameVisible && this.state.groupName}
                            {
                                this.state.editGroupNameVisible &&
                                <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@t9x1dh`}
                                    // helpfulTip="测试"
                                    className="updateStageName"
                                    autofocus="autofocus"
                                    style={{ top: '6px' }}
                                    value={this.state.groupName}
                                    onChange={value => {
                                        this.setState({ groupName: value })
                                    }}
                                />
                            }
                        </div>
                        <div className="kanban-group-head-extra" style={{ display: canEditBoard ? this.state.editGroupNameVisible ? "none" : "" : "none" }}>
                            <Dropdown ecId={`${this && this.props && this.props.ecId || ''}_Dropdown@azu1jz`} overlay={menu}>
                                <span className="icon-coms-List column-header-menu"></span>
                            </Dropdown>
                        </div>
                    </div>
                </div>
                <div ref={ref => this.body = ref} className="kanban-group-body">
                    {React.Children.map(this.props.children, (child) => {
                        return React.cloneElement(child, { root: this.props.root, xScroller: this.props.scroller, yScroller: this.body });
                    })}
                </div>
                <div ref={ref => this.footer = ref} className="kanban-group-footer" >
                    <div style={{ display: canAddTask ? "" : "none",height: "100%" }} >
                        <div className="btnBottomNew" onClick={() => { this.showAddComs() }} >+{getLabel('84046', "新任务")}</div>
                        <div className="footer-card" style={{ display: !this.state.visible ? "none" : "" }}>
                            <div className="card-content">
                                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@26vqez`} style={{ lineHeight: "30px", padding: "6px 17px" }}>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8q012z`} span={8}>
                                        {getLabel('1352', "任务名称")}：
                                    </Col>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@k215c4`} span={14}>
                                        <div className={this.state.taskInfo.taskName ? "" : "required"} >
                                        <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@4vd6an`} tipPosition='bottom'
                                        ref='taskname'
                                        error={getLabel('387696', "任务名称未填写！")}>
                                            <Input ecId={`${this && this.props && this.props.ecId || ''}_Input@vk0k8g`}
                                                // ref={"area_"+this.props.groupid}
                                                ref={(input) => { this.textInput = input; }}
                                                type="textarea"
                                                // disabled={disabled}
                                                autofocus="autofocus"
                                                autosize={{ minRows: "1", maxRows: "1" }}
                                                value={this.state.taskInfo.taskName}
                                                id={"area_" + this.props.groupid}
                                                onChange={(v) => this.setTaskValue("subject", v)}
                                                // onBlur={()=>{ this.showAddComs() }}
                                                placeholder={getLabel('1352', "任务名称")}
                                            />
                                        </WeaError>
                                        </div>
                                    </Col>
                                </Row>
                                <div className="clearFix" />
                                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@iu08pe`} style={{ lineHeight: "30px", padding: "6px 17px", width:400 }}>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@cwpqjn`} span={8} style={{width:77.98}}>
                                        {getLabel('2097', "负责人")}：
                                    </Col>
                                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@956ov5`} tipPosition='bottom'
                                                ref='taskhrm'
                                                error={getLabel('387699', "任务负责人未选择！")}
                                                style={{width:"64%"}}
                                                >
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@bu07ih`} span={14}>
                                        <div className="kanban-group-manager managericons" >
                                            <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@r5r2c7`} placement="left" title={this.props.username}>
                                                {/* <a href={'javaScript:openhrm(' + this.props.userid + ');'} onClick={e => window.pointerXY(e)} >
                                                    <img src={this.props.usericons} className="kanban-group-manager-img" />
                                                </a> */}
                                                <div className={this.state.taskInfo.hrmid ? "" : "required"} >
                                                
                                                    <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@he1goy`}
                                                        type={17}
                                                        // customized
                                                        key={this.state.taskInfo.hrmname}
                                                        replaceDatas={[{ id: this.state.taskInfo.hrmid, name: this.state.taskInfo.hrmname }]}
                                                        textDecoration={true}
                                                        isSingle={false}
                                                        onChange={(ids, names, datas) => this.setTaskValue("hrmid", { hrmid: ids, hrmname: names })}
                                                    >
                                                        {/* <Tooltip placement="bottom" title={this.state.taskInfo.hrmname == "" ? "请选择任务负责人" : this.state.taskInfo.hrmname}>
                                                            <img src={"/messager/images/icon_w_wev8.jpg"} className="kanban-group-manager-img" />
                                                        </Tooltip> */}
                                                    </WeaBrowser>
                                                </div>
                                            </Tooltip>
                                        </div>
                                        {/* <div style={{marginLeft:"50px"}}>{this.state.taskInfo.hrmname}</div> */}
                                    </Col>
                                    </WeaError>
                                </Row>
                                <div className="clearFix" />
                                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@rfhdub`} style={{ lineHeight: "30px", padding: "6px 17px", width:400 }}>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@hz080a`} span={8} style={{width:77.98}}>
                                        {getLabel('24979', "开始时间")}：
                                    </Col>
                                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@vr2xuh`} tipPosition='bottom'
                                                ref='taskstart'
                                                error={getLabel('387697', "任务开始时间未选择！")}
                                                style={{width:"64%"}}>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@wrom2s`} span={14}>
                                        <div className="content-landmark" >
                                            {/* <WeaRangePicker
                                                value={[this.state.taskInfo.startDate, this.state.taskInfo.endDate]}
                                                onChange={v => this.setTaskValue("startendDate",v)}
                                            /> */}
                                            
                                            <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@mrvzs3`}
                                                noInput
                                                value={this.state.taskInfo.startDate}
                                                onChange={v => this.setTaskValue("startDate", v)}
                                                key={this.state.taskInfo.startDate}
                                            />
            
                                        </div>
                                    </Col>
                                    </WeaError>
                                </Row>
                                <div className="clearFix" />
                                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@vihujq`} style={{ lineHeight: "30px", padding: "6px 17px", width:400 }}>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@92zokn`} span={8} style={{width:77.98}}>
                                        {getLabel('743', "结束时间")}：
                                    </Col>
                                    <WeaError ecId={`${this && this.props && this.props.ecId || ''}_WeaError@f229jb`} tipPosition='bottom'
                                                ref='taskend'
                                                error={getLabel('387698', "任务结束时间未选择！")}
                                                style={{width:"64%"}}>
                                    <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@f4s8vq`} span={14}>
                                        <div className="content-landmark" >
                                            {/* <WeaRangePicker
                                                value={[this.state.taskInfo.startDate, this.state.taskInfo.endDate]}
                                                onChange={v => this.setTaskValue("startendDate",v)}
                                            /> */}
                                            <WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@imtuw0`}
                                                noInput
                                                value={this.state.taskInfo.endDate}
                                                onChange={v => this.setTaskValue("endDate", v)}
                                                key={this.state.taskInfo.endDate}
                                            />
                                        </div>
                                    </Col>
                                    </WeaError>
                                </Row>
                            </div>
                            <div className="btnBottomSubmit" onClick={() => { this.closeAddComs() }} >{getLabel('31129', "取消")}</div>
                            <div className="btnBottomSubmit" onClick={() => { this.showAddComs() }} >{getLabel('33703', "确认")}</div>
                        </div>
                    </div>
                </div>

            </div>
        )
    }

    getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate;
        return currentdate;
    }

    closeAddComs = (bool) => {
        const { userInfo } = this.props;
        this.setState({
            taskInfo: {
                taskName: "",
                hrmid: userInfo.userid,
                hrmname: userInfo.username,
                startDate: this.getNowFormatDate(),
                endDate: this.getNowFormatDate(),
            },
            userInfo: {
                userid: userInfo.userid,
                username: userInfo.username,
                usericons: userInfo.usericons
            },
        });
        this.setState({ visible: !this.state.visible });

    }

    showAddComs = () => {
        let checked = true;
        const that = this;
        if (this.state.visible) {
            if (!this.state.taskInfo.taskName) {
                this.refs.taskname.showError();
                checked = false;
            } else if (!this.state.taskInfo.hrmid) {
                this.refs.taskhrm.showError();
                checked = false;
            } else if (!this.state.taskInfo.startDate) {
                this.refs.taskstart.showError();
                checked = false;
            } else if (!this.state.taskInfo.endDate) {
                this.refs.taskend.showError();
                checked = false;
            } else if (this.state.taskInfo.endDate < this.state.taskInfo.startDate) {
                message.error(getLabel('387700', "任务结束时间必须大于任务开始时间！"));
                checked = false;
            }
            if (checked) {
                this.props.saveTask({
                    stageid: this.props.groupid,
                    subject: this.state.taskInfo.taskName,
                    begindate: this.state.taskInfo.startDate,
                    enddate: this.state.taskInfo.endDate,
                    hrmid: this.state.taskInfo.hrmid,
                });
                const { userid, username, usericons } = this.props;
                this.setState({
                    taskInfo: {
                        taskName: "",
                        hrmid: userid,
                        startDate: "",
                        endDate: ""
                    },
                    userInfo: {
                        userid: userid,
                        username: username,
                        usericons: usericons
                    }
                });
                this.setState({ visible: !this.state.visible });
            }


        } else {
            checked && this.setState({ visible: !this.state.visible });
            // jQuery("#area_"+this.props.groupid).focus()
            // this.refs.area+this.props.groupid.focus();
        }


    }

    setTaskValue = (fieldname, v) => {
        if (fieldname == "startDate") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    startDate: v,
                },
            });
        } else if (fieldname == "endDate") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    endDate: v,
                },
            });
        } else if (fieldname == "subject") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    taskName: jQuery("#area_" + this.props.groupid).val()
                },
            });
        } else if (fieldname == "hrmid") {
            this.setState({
                taskInfo: {
                    ...this.state.taskInfo,
                    hrmid: v.hrmid,
                    hrmname: v.hrmname,
                },
            });
        }
    }

    setDate = (date) => {
        this.setState({
            taskInfo: {
                ...this.state.taskInfo,
                startDate: date[0],
                endDate: date[1]
            },
        });
    }
    setTaskName = () => {
        let taskName = jQuery("#area_" + this.props.groupid).val();
        this.setState({
            taskInfo: {
                ...this.state.taskInfo,
                taskName: taskName,
            },
        });
    }


    handleHeadMouseDown = (ev) => {
        const { canEditBoard } = this.props;
        this.offset = {
            left: this.container.offsetLeft - jQuery(this.container).closest('.kanban-scroller')[0].scrollLeft,
            top: this.container.offsetTop,
            height: this.container.clientHeight,
            width: this.container.clientWidth,
            startX: ev.clientX,
            startY: ev.clientY
        };
        this.startScrollX =jQuery(this.container).closest('.kanban-scroller')[0].scrollLeft;
        canEditBoard && document.addEventListener('mousemove', this.handleMouseMove);
        canEditBoard && document.addEventListener('mouseup', this.handleMouseUp);
    }
    handleMouseMove = (ev) => {
        let diffX = ev.clientX - this.offset.startX;
        const f = jQuery(this.container).closest('.kanban-scroller')[0].scrollWidth / jQuery(this.container).closest('.kanban-scroller')[0].clientWidth;
        if (Math.abs(diffX) > 5) {
            this.props.root.moving = true;
            this.moving = true;
            this.container.style.position = 'absolute';
            this.container.style.width = this.offset.width + 'px';
            this.container.style.height = this.offset.height + 'px';
            this.container.style.left = (this.offset.left - 10 + diffX) + 'px';
            this.container.style.top = (this.offset.top - 10) + 'px';
            this.container.style.zIndex = 1000;
            jQuery(this.container).addClass('moving');
            this.props.root.showPlace(this.offset, this.container);
            if (diffX < 0) {
                jQuery(this.container).prevAll('.kanban-group').each((index, ele) => {
                    const offset = jQuery(ele).offset();
                    const width = jQuery(ele).width();
                    const height = jQuery(ele).height();
                    const offset1 = jQuery(this.container).offset();
                    const width1 = jQuery(this.container).width();
                    const middle = offset.left + width / 2 - offset1.left;
                    if (middle > 0 && (middle < width1 || index === 0)) {
                        this.props.root.showPlace({ width, height }, ele);
                    }
                })
            } else {
                const nextAll = jQuery(this.container).nextAll('.kanban-group');
                nextAll.each((index, ele) => {
                    const offset = jQuery(ele).offset();
                    const width = jQuery(ele).width();
                    const height = jQuery(ele).height();
                    const offset1 = jQuery(this.container).offset();
                    const width1 = jQuery(this.container).width();
                    const middle = offset1.left + width1 - offset.left - width / 2;
                    if (middle > 0 && (middle < width / 2 || index === nextAll.length - 1)) {
                        this.props.root.showPlace({ width, height }, ele, true);
                    }
                })
            }
            jQuery(this.container).closest('.kanban-scroller')[[0]].scrollLeft = this.startScrollX + diffX * f;
        }
    }
    handleMouseUp = () => {
        document.removeEventListener('mousemove', this.handleMouseMove);
        document.removeEventListener('mouseup', this.handleMouseUp);
        if (this.moving) {
            this.container.style.removeProperty('position');
            this.container.style.removeProperty('width');
            this.container.style.removeProperty('height');
            this.container.style.removeProperty('left');
            this.container.style.removeProperty('top');
            this.container.style.removeProperty('z-index');
            this.props.root.moving = false;
            this.moving = false;
            jQuery(this.container).removeClass('moving');
            this.props.root.container.insertBefore(this.container, this.props.root.place);
            this.props.root.hidePlace();
            this.props.root.onChange();
        }
    }

}
